<template>
  <view class="detail-container">
    <!-- 班级标题 -->
    <view class="class-header">
      <text class="class-title">{{ displayClassName }}</text>
      <text class="record-count">共 {{ violationList.length }} 条违纪记录</text>
    </view>

    <!-- 违纪记录列表 -->
    <view class="violation-list">
      <view 
        v-for="(item, index) in violationList" 
        :key="item.id"
        class="violation-item"
      >
        <!-- 日期和状态 -->
        <view class="item-header">
          <view class="date-info">
            <!-- <text class="date-icon">📅</text> -->
            <text class="date-text">{{ item.classDate }} {{ item.classTime }}</text>
          </view>
          <text :class="['status-badge', getStatusClass(item.status)]">
            {{ getStatusText(item.status) }}
          </text>
        </view>

        <!-- 课程信息 -->
        <view class="course-info">
          <view class="info-row">
            <text class="label">课程:</text>
            <text class="value">{{ item.courseName || '未知' }}</text>
          </view>
          <view class="info-row">
            <text class="label">教师:</text>
            <text class="value">{{ item.teacherName || '未知' }}</text>
          </view>
          <view class="info-row">
            <text class="label">教室:</text>
            <text class="value">{{ item.classroom || '未知' }}</text>
          </view>
        </view>

        <!-- 违纪类型 -->
        <view class="violation-info">
          <text class="violation-label">违纪情况:</text>
          <text class="violation-text">{{ item.violationType }}</text>
          <text class="violation-count">({{ item.violationCount }}人)</text>
        </view>

        <!-- 违纪描述 -->
        <view v-if="item.violationDesc" class="violation-desc">
          <text class="desc-label">详细描述:</text>
          <text class="desc-text">{{ item.violationDesc }}</text>
        </view>

        <!-- 巡班老师 -->
        <view class="patrol-info">
          <text class="patrol-label">巡班教师:</text>
          <text class="patrol-name">{{ item.patrolTeacherName || '未知' }}</text>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="violationList.length === 0 && !loading" class="empty-state">
        <text class="empty-icon">📋</text>
        <text class="empty-text">暂无违纪记录</text>
      </view>

      <!-- 加载中 -->
      <view v-if="loading" class="loading-state">
        <text>加载中...</text>
      </view>
    </view>
  </view>
</template>

<script>
  import config from '@/config'
  
  export default {
    data() {
      return {
        className: '',
        displayClassName: '', // 用于显示的班级名（去除前导0）
        filterDate: '',
        startDate: '',
        endDate: '',
        violationList: [],
        loading: false
      }
    },
    onLoad(options) {
      this.className = decodeURIComponent(options.className || '')
      this.displayClassName = this.removeLeadingZeros(this.className)
      this.filterDate = options.filterDate || ''
      
      // 如果有startDate和endDate参数，转换为classDate范围
      if (options.startDate && options.endDate) {
        this.startDate = options.startDate
        this.endDate = options.endDate
      }
      
      // 设置导航栏标题
      uni.setNavigationBarTitle({
        title: this.displayClassName + ' - 违纪详情'
      })
      
      this.loadViolations()
    },
    methods: {
      // 去掉班级名称前面的0
      removeLeadingZeros(className) {
        // 1. 去除开头的0: "0高技2404班" -> "高技2404班"
        // 2. 去除数字中的前导0: "0210" -> "210"
        let result = className.replace(/^0+([^0])/g, '$1')  // 去除开头的0
        result = result.replace(/(\D)0+(\d)/g, '$1$2')  // 去除非数字后的0
        return result
      },
      // 加载违纪记录
      async loadViolations() {
        this.loading = true
        try {
          const token = uni.getStorageSync('App-Token')
          
          // 分页加载所有数据
          let allViolations = []
          let pageNo = 1
          const pageSize = 100 // 后端限制最大100
          let hasMore = true
          
          // console.log('开始分页加载违纪记录...')
          // console.log('当前班级名称:', this.className)
          
          while (hasMore) {
            const params = {
              pageNo: pageNo,
              pageSize: pageSize
            }
            
            // 日期参数需要转换为日期范围数组 [开始日期, 结束日期]
            if (this.filterDate) {
              params.classDate = [
                `${this.filterDate} 00:00:00`,
                `${this.filterDate} 23:59:59`
              ]
            } else if (this.startDate && this.endDate) {
              // 使用时间范围查询
              params.classDate = [
                `${this.startDate} 00:00:00`,
                `${this.endDate} 23:59:59`
              ]
            }
            
            const res = await uni.request({
              url: config.baseUrl + '/admin-api/ao/patrol/page',
              method: 'GET',
              header: {
                'Authorization': 'Bearer ' + token,
                'tenant-id': '1',
                'Content-Type': 'application/json'
              },
              data: params
            })

            if (res[1] && res[1].data && res[1].data.code === 0 && res[1].data.data) {
              const pageData = res[1].data.data
              allViolations = allViolations.concat(pageData.list || [])
              
              // console.log(`第${pageNo}页加载完成, 本页${pageData.list?.length || 0}条, 累计${allViolations.length}条`)
              
              // 判断是否还有更多数据
              if (pageData.list && pageData.list.length === pageSize && allViolations.length < pageData.total) {
                pageNo++
              } else {
                hasMore = false
              }
            } else {
              console.error('加载第' + pageNo + '页失败:', res[1]?.data)
              hasMore = false
            }
          }

          // console.log('所有数据加载完成, 总计:', allViolations.length, '条')
          
          // 自动删除"无违纪"记录
          const noViolationRecords = allViolations.filter(item => 
            item.violationType === '无违纪' || item.violationCount === 0
          )
          
          if (noViolationRecords.length > 0) {
            console.log('检测到', noViolationRecords.length, '条无违纪记录，正在删除...')
            // 批量删除无违纪记录
            for (const record of noViolationRecords) {
              try {
                await uni.request({
                  url: config.baseUrl + `/admin-api/ao/patrol/delete?id=${record.id}`,
                  method: 'DELETE',
                  header: {
                    'Authorization': 'Bearer ' + token,
                    'tenant-id': '1'
                  }
                })
              } catch (err) {
                console.error('删除无违纪记录失败:', record.id, err)
              }
            }
            console.log('无违纪记录删除完成')
          }
          
          if (allViolations.length > 0) {
            // 前端过滤: 只保留当前班级的真实违纪记录
            const filteredList = allViolations.filter(item => {
              // 直接比较原始班级名 AND 排除无违纪
              return item.className === this.className 
                && item.violationType !== '无违纪' 
                && item.violationCount > 0
            })
            
            // console.log('过滤前总数:', allViolations.length)
            // console.log('过滤后数量:', filteredList.length)
            // console.log('查询班级名:', this.className)
            
            if (filteredList.length === 0) {
              // console.log('⚠️ 没有找到匹配的记录!')
              // console.log('所有班级名称:', [...new Set(allViolations.map(v => v.className))])
            }
            
            // 按日期倒序排列
            this.violationList = filteredList.sort((a, b) => {
              return new Date(b.classDate) - new Date(a.classDate)
            })
          } else {
            this.violationList = []
          }
        } catch (err) {
          console.error('加载违纪记录失败:', err)
          uni.showToast({
            title: '加载失败',
            icon: 'none'
          })
        } finally {
          this.loading = false
        }
      },

      // 获取状态文本
      getStatusText(status) {
        const statusMap = {
          0: '待处理',
          1: '已处理',
          2: '已忽略'
        }
        return statusMap[status] || '未知'
      },

      // 获取状态样式类
      getStatusClass(status) {
        const classMap = {
          0: 'status-pending',
          1: 'status-done',
          2: 'status-ignore'
        }
        return classMap[status] || 'status-pending'
      }
    }
  }
</script>

<style lang="scss" scoped>
  page {
    background-color: #f5f5f5;
  }

  .detail-container {
    min-height: 100vh;
    padding-bottom: 20px;
  }

  /* 班级标题 */
  .class-header {
    position: relative;
    background-image: url("/RuoYi-App-master/static/images/banner/banner01.jpg");
    background-size: cover;
    background-position: center;
    padding: 25px 20px;
    color: white;
    
    /* 添加深色遮罩,让文字更清晰 */
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5); /* 黑色半透明遮罩 */
      z-index: 0;
    }
  }

  .class-title {
    position: relative;
    z-index: 1;
    display: block;
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 8px;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3); /* 添加文字阴影 */
  }

  .record-count {
    position: relative;
    z-index: 1;
    font-size: 14px;
    opacity: 0.95;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); /* 添加文字阴影 */
  }

  /* 违纪记录列表 */
  .violation-list {
    padding: 0 15px;
  }

  .violation-item {
    background: white;
    border-radius: 12px;
    padding: 15px;
    margin-top: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  }

  /* 项头部 */
  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 12px;
  }

  .date-info {
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .date-icon {
    font-size: 16px;
  }

  .date-text {
    font-size: 14px;
    color: #666;
  }

  .status-badge {
    padding: 3px 10px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
  }

  .status-pending {
    background: #fff3e0;
    color: #f57c00;
  }

  .status-done {
    background: #e8f5e9;
    color: #388e3c;
  }

  .status-ignore {
    background: #f5f5f5;
    color: #999;
  }

  /* 课程信息 */
  .course-info {
    margin-bottom: 12px;
  }

  .info-row {
    display: flex;
    padding: 4px 0;
    font-size: 14px;
  }

  .info-row .label {
    width: 60px;
    color: #999;
    flex-shrink: 0;
  }

  .info-row .value {
    flex: 1;
    color: #333;
  }

  /* 违纪信息 */
  .violation-info {
    background: #fff3e0;
    padding: 10px;
    border-radius: 6px;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .violation-label {
    font-size: 13px;
    color: #f57c00;
    margin-right: 8px;
  }

  .violation-text {
    font-size: 14px;
    color: #333;
    font-weight: 500;
    margin-right: 8px;
  }

  .violation-count {
    font-size: 13px;
    color: #f57c00;
  }

  /* 违纪描述 */
  .violation-desc {
    background: #f5f5f5;
    padding: 10px;
    border-radius: 6px;
    margin-bottom: 12px;
  }

  .desc-label {
    display: block;
    font-size: 12px;
    color: #999;
    margin-bottom: 5px;
  }

  .desc-text {
    font-size: 14px;
    color: #666;
    line-height: 1.6;
  }

  /* 巡班老师 */
  .patrol-info {
    display: flex;
    align-items: center;
    font-size: 13px;
  }

  .patrol-label {
    color: #999;
    margin-right: 8px;
  }

  .patrol-name {
    color: #667eea;
    font-weight: 500;
  }

  /* 空状态 */
  .empty-state {
    text-align: center;
    padding: 60px 20px;
  }

  .empty-icon {
    display: block;
    font-size: 60px;
    margin-bottom: 15px;
    opacity: 0.3;
  }

  .empty-text {
    font-size: 14px;
    color: #999;
  }

  /* 加载状态 */
  .loading-state {
    text-align: center;
    padding: 30px;
    color: #999;
    font-size: 14px;
  }
</style>
